package com.fz.us.admin.dict.service.impl;

import com.fz.us.admin.base.bean.Result;
import com.fz.us.admin.base.dao.BaseDao;
import com.fz.us.admin.base.service.impl.BaseServiceImpl;
import com.fz.us.admin.dict.dao.DictItemDao;
import com.fz.us.admin.dict.dto.DictItemDto;
import com.fz.us.admin.dict.entity.Dict;
import com.fz.us.admin.dict.entity.DictItem;
import com.fz.us.admin.dict.service.DictItemService;
import com.fz.us.admin.dict.service.DictItemSettingService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Service实现类 - 字典 item
 * ============================================================================
 * 版权所有 2016 。
 *
 * @author fallenpanda
 * @version 1.0 2016-07-19 。
 * ============================================================================
 */
@Service
public class DictItemServiceImpl extends BaseServiceImpl<DictItem, String> implements DictItemService {

    @Resource
    private DictItemDao dictItemDao;
    @Override
    public BaseDao<DictItem, String> getBaseDao() {
        return dictItemDao;
    }

    @Resource
    private DictItemSettingService dictSettingService;

    @Override
    public List<DictItem> listSystem(String dictId) {
        return dictItemDao.listSystem(dictId);
    }

    @Override
    public List<DictItemDto> listDefault(String dictId, String keyId) {
        return dictItemDao.listDefault(dictId, keyId);
    }

    @Override
    public List<DictItemDto> listSelectableDefined(String dictId, String keyId) {
        return dictItemDao.listSelectableDefined(dictId, keyId);
    }

    @Override
    public DictItem getByValue(String dictId, String value){
        return dictItemDao.getByValue(dictId, value);
    }

    @Override
    public DictItem getByValue(String dictId, String keyId, String value) {
        return dictItemDao.getByValue(dictId, keyId, value);
    }

    @Override
    public boolean isExistValue(String dictId, String value) {
        return getByValue(dictId, value) != null;
    }

    @Override
    public boolean isExistValue(String dictId, String keyId, String value) {
        return getByValue(dictId, keyId, value) != null;
    }

    @Override
    public int getMaxSortNo(String dictId, String keyId) {
        return dictItemDao.getMaxSortNo(dictId, keyId);
    }

    @Override
    public String getDefinedName(String keyId, String dictItemId) {
        return dictSettingService.getDefinedName(keyId, dictItemId);
    }

    @Override
    public Result addDefault(Dict dict, String name, String value, String description, int ifKey, int ifSelectable, int sortNo, DictItem parent){
        Assert.notNull(dict, "dict is required");
        Assert.hasText(name, "name is required");

        if (StringUtils.isNotEmpty(value)) {
            if (isExistValue(dict.getId(), value)) {
                return resultService.fail("关键字已存在");
            }
        }

        DictItem dictItem = new DictItem(dict, name, value, description, ifKey, ifSelectable, sortNo, parent);
        return saveEntity(dictItem);
    }

    @Override
    public Result addDefined(Dict dict, String keyId, String name, String value, String description, DictItem parent) {
        int maxSortNo = getMaxSortNo(dict.getId(), keyId);
        DictItem dictItem = new DictItem(dict, keyId, name, value, description, maxSortNo + 1, parent);
        return saveEntity(dictItem);
    }

    @Override
    public Result editDefined(String dictitemId, String name, String value, String description, int ifKey, int ifSelectable, int sortNo) {
        Assert.hasText(dictitemId, "dictitemId is required");
        Assert.hasText(name, "name is required");

        DictItem dictItemTemp = get(dictitemId);
        if (StringUtils.isNotEmpty(value) && !StringUtils.equals(dictItemTemp.getValue(), value)) {
            if (isExistValue(dictItemTemp.getDict().getId(), value)) {
                return resultService.fail("关键字已存在");
            }
        }

        dictItemTemp.setName(name);
        dictItemTemp.setValue(value);
        dictItemTemp.setDescription(description);
        dictItemTemp.setIfKey(ifKey);
        dictItemTemp.setIfSelectable(ifSelectable);
        dictItemTemp.setSortNo(sortNo);

        update(dictItemTemp);

        return resultService.successWithId(dictItemTemp.getId());
    }

    @Override
    public Result editDefined(String dictitemId, String name, String description) {
        Assert.hasText(dictitemId, "dictitemId is required");
        Assert.hasText(name, "name is required");

        DictItem dictItemTemp = get(dictitemId);
        dictItemTemp.setName(name);
        dictItemTemp.setDescription(description);

        update(dictItemTemp);

        return resultService.successWithId(dictItemTemp.getId());
    }

    @Override
    public Result sort(String action, String dictitemId, String targetId, String[] ids) {
        Assert.hasText(action, "action is required");
        Assert.hasText(dictitemId, "dictitemId is required");
        Assert.hasText(targetId, "targetId is required");

        DictItem dictItem = get(dictitemId);
        DictItem dictItemTarget = get(targetId);

        if (StringUtils.equals("Up", action)) {// 上移
            if (dictItemTarget.getIfSystem() == 1) {
                if (ids != null && ids.length > 0) {// +1
                    DictItem dictItemTemp = get(ids[0]);
                    int sortNo = dictItemTemp.getSortNo();

                    dictItem.setSortNo(sortNo+1);
                    update(dictItem);

                    return resultService.success();
                } else {// 顶置
                    dictItem.setSortNo(0);
                    update(dictItem);

                    return resultService.success();
                }
            } else {// 互换 sortNo
                int sortNo = dictItemTarget.getSortNo();
                dictItemTarget.setSortNo(dictItem.getSortNo()==0?1:dictItem.getSortNo());
                update(dictItemTarget);

                dictItem.setSortNo(sortNo);
                update(dictItem);

                return resultService.success();
            }
        } else if (StringUtils.equals("Down", action)) {// 下移
            if (dictItemTarget.getIfSystem() == 1) {
                int sortNo = dictItemTarget.getSortNo();

                sortNo++;
                dictItem.setSortNo(sortNo);
                update(dictItem);

                if (ids != null && ids.length > 0) {
                    for (int i=0;i<ids.length;i++) {
                        DictItem dictItemTemp = get(ids[i]);
                        sortNo++;
                        dictItemTemp.setSortNo(sortNo);
                        update(dictItemTemp);
                    }
                }
            } else {// 互换 sortNo
                int sortNo = dictItemTarget.getSortNo();
                dictItemTarget.setSortNo(dictItem.getSortNo());
                update(dictItemTarget);

                dictItem.setSortNo(sortNo==0?1:sortNo);
                update(dictItem);

                return resultService.success();
            }

            return resultService.success();
        }

        return resultService.fail();
    }

    @Override
    public Map<String, Object> getListMap(DictItem dictItem) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("dictId", "");
        map.put("dictName", "");
        if (dictItem.getDict() != null) {
            Dict dict = dictItem.getDict();
            map.put("dictId", dict.getId());
            map.put("dictName", dict.getName());
        }

        map.put("id", StringUtils.isEmpty(dictItem.getId())?"":dictItem.getId());
        map.put("ifSystem", dictItem.getIfSystem());
        map.put("keyId", StringUtils.isEmpty(dictItem.getKeyId())?"":dictItem.getKeyId());
        map.put("name", StringUtils.isEmpty(dictItem.getName())?"":dictItem.getName());
        map.put("pinYinHead", StringUtils.isEmpty(dictItem.getPinYinHead())?"":dictItem.getPinYinHead().toLowerCase());
        map.put("pinYin", StringUtils.isEmpty(dictItem.getPinYin())?"":dictItem.getPinYin());

        map.put("value", StringUtils.isEmpty(dictItem.getValue())?"":dictItem.getValue());
        map.put("description", StringUtils.isEmpty(dictItem.getDescription())?"":dictItem.getDescription());
        map.put("ifKey", dictItem.getIfKey());
        map.put("ifSelectable", dictItem.getIfSelectable());
        map.put("sortNo", dictItem.getSortNo());

        // other
        map.put("state", dictItem.getState()==null?"":dictItem.getState().name());

        return map;
    }

    @Override
    public Map<String, Object> getDetailMap(DictItem dictItem) {
        return getListMap(dictItem);
    }

    @Override
    public Map<String, Object> getListMap(DictItemDto dictItem) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("dictId", StringUtils.isEmpty(dictItem.dictId)?"":dictItem.dictId);

        map.put("id", StringUtils.isEmpty(dictItem.id)?"":dictItem.id);
        map.put("ifSystem", dictItem.ifSystem);
        map.put("keyId", StringUtils.isEmpty(dictItem.keyId)?"":dictItem.keyId);
        map.put("name", StringUtils.isEmpty(dictItem.name)?"":dictItem.name);

        map.put("value", StringUtils.isEmpty(dictItem.value)?"":dictItem.value);
        map.put("description", StringUtils.isEmpty(dictItem.description)?"":dictItem.description);
        map.put("ifKey", dictItem.ifKey);
        map.put("ifSelectable", dictItem.ifSelectable);
        map.put("sortNo", dictItem.sortNo);
        map.put("state", StringUtils.isEmpty(dictItem.state)?"":dictItem.state);

        map.put("parentId", StringUtils.isEmpty(dictItem.parentId)?"":dictItem.parentId);

        map.put("sId", StringUtils.isEmpty(dictItem.sId)?"":dictItem.sId);
        map.put("sName", StringUtils.isEmpty(dictItem.sName)?"":dictItem.sName);
        map.put("sState", StringUtils.isEmpty(dictItem.sState)?"":dictItem.sState);

        return map;
    }

    @Override
    public Map<String, Object> getSelectMap(DictItemDto dictItem) {
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("id", StringUtils.isEmpty(dictItem.id)?"":dictItem.id);
        if (StringUtils.isNotEmpty(dictItem.sName)) {
            map.put("name", dictItem.sName);
            map.put("pinYinHead", dictItem.sPinYinHead);
            map.put("pinYin", dictItem.sPinYin);
        } else {
            map.put("name", dictItem.name);
            map.put("pinYinHead", dictItem.pinYinHead);
            map.put("pinYin", dictItem.pinYin);
        }
        map.put("description", StringUtils.isEmpty(dictItem.description)?"":dictItem.description);

        return map;
    }

}
